import axios from 'axios'
import { delToken, getToken } from './auth'

import { BASE_URL } from './url'

const API = axios.create({
  baseURL: BASE_URL
})

// 请求拦截器
API.interceptors.request.use(config => {
  const { url } = config
  let token = getToken()
  if (token) {
    token = JSON.parse(token)['token']
  }

  if (url.startsWith('/user') && !url.startsWith('/user/login') && !url.startsWith('/user/registered')) {
    config.headers.Authorization = token
  }
  return config
})

// 响应拦截器
API.interceptors.response.use(response => {
  const { status } = response.data
  if (status === 400) {
    delToken()
  }

  return response
})

export { API }